NAME=$(basename "$0")

case ${NAME} in
	gnap_make )     GNAP_PRODUCT="Build";;
 	gnap_overlay )  GNAP_PRODUCT="Overlay";;
 	gnap_remaster ) GNAP_PRODUCT="Remaster";;
 	* )             GNAP_PRODUCT="Something";;
esac

GNAP_STAGE3FILE=${GNAP_STAGE3FILE:-"${GNAP_LIBDIR}/gnap-stage3seed.tar.bz2"}
GNAP_SNAPSHOTFILE=${GNAP_SNAPSHOTFILE:-"${GNAP_LIBDIR}/gnap-portagesnapshot.tar.bz2"}
GNAP_SPECS=${GNAP_SPECS:-"${GNAP_LIBDIR}/gnap-specs.tar.bz2"}
GNAP_CORE=${GNAP_CORE:-"${GNAP_LIBDIR}/gnap-core.tar"}
GNAP_MBR=${GNAP_MBR:-"${GNAP_LIBDIR}/mbr/mbr.bin"}
GNAP_EXTDIR=${GNAP_EXTDIR:-"${GNAP_LIBDIR}/extensions"}
GNAP_BASEFS=${GNAP_BASEFS:-"${GNAP_LIBDIR}/gnap-basefs.tar.bz2"}

GNAP_FORCEYES=${GNAP_FORCEYES:-0}

#CONTINUED=0
TEMPDIR=''
LOOP=''

G=$'\e[32;01m' # green
B=$'\e[31;01m' # red
N=$'\e[0m'     # neutral
W=$'\e[33;01m' # yellow
K=$'\e[34;01m' # blue
C="$[$(set -- $(stty size 2>/dev/null); echo ${2}) - 7]" # end of line helper
E=$'\e['${C}'G' # end of line

ginfo() {
	echo -e " ${G}*${N} ${*}"
}

gwarn() {
	echo -e " ${W}*${N} ${*}"
}

gdie() {
	echo -e " ${B}*${N} ${*}"
	cleanup
	exit 1
}


gmkdir() {
	mkdir -p "$1"
	gtest continued $? "Failed to create \"$1\"."
}

gconfirm() {
	if [[ "${GNAP_FORCEYES}" -eq 1 ]]; then
		gwarn "${*} forced to yes"
	else
		read -ep " ${W}*${N} ${*} [N]: " answer
		[[ "${answer}" != 'y' && "${answer}" != 'Y' ]] && \
			gdie "${GNAP_PRODUCT} aborted!"
	fi
}

gbegin() {
#	[[ "${CONTINUED}" -eq 1 ]] && gdie "BUG triggered by gbegin()"

	echo -ne " ${G}*${N} ${*}..."
#	CONTINUED=1
}

gtest() {
#	# TODO: Remove this after removing all "gtest continued"
#	if [[ "${#}" -gt 0 && "${1}" == 'continued' ]]; then
#		shift
#	fi
	CONTINUED=0
	if [[ "${#}" -gt 0 && "${1}" == 'continued' ]]; then
		CONTINUED=1
		shift
	fi

	if [[ "${#}" -eq 0 || "${1}" -eq 0 ]]; then
		if [[ "${CONTINUED}" -eq 0 ]]; then
			echo -e "${E}  ${K}[ ${G}ok${K} ]${N}"
		fi
	else
		echo -e "${E}  ${K}[ ${B}!!${K} ]${N}"
		if [[ "${#}" -ge 2 ]]; then
			shift
			echo -en " ${B}*${N} ${*}"
			echo -e "${E}  ${K}[ ${B}!!${K} ]${N}"
		fi
		gdie "${GNAP_PRODUCT} failed, try man ${NAME} for more help"
	fi
}

cleanup() {
	if [[ -n "${LOOP}" ]]; then
		gbegin 'Unmounting loop filesystem'
		umount "${LOOP}" && losetup -d "${LOOP}"
		gtest $? "Failed to unmount ${LOOP}"
	fi
	if [[ -d "${TEMPDIR}" ]]; then
		gbegin 'Cleaning temporary directories'
		rm -rf "${TEMPDIR}"
		gtest $? "Failed to remove ${DIRTOREMOVE}"
		TEMPDIR=''
	fi
}
